<template>
  <t-card>
    <t-space direction="vertical" style="width: 100%">
      <t-form v-show="showSearch" ref="queryRef" :data="queryParams" layout="inline" reset-type="initial" label-width="calc(4em + 12px)" label-align="top">
        <t-form-item label="编号" name="wonderfulImageId">
          <t-input v-model="queryParams.wonderfulImageId" placeholder="请输入编号" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label="环保新闻" name="conferenceInfo" >
            <t-select v-model="queryParams.conferenceInfoId"
                      clearable placeholder="请选择环保新闻"
                      :scroll="{ type: 'virtual' }"
                      :popup-props="{ overlayInnerStyle: { height: '150px',width:'500px' } }"
                      auto-width
            >
                <template #prefixIcon>
                    <browse-icon style="margin-right: 8px" />
                </template>
                <template #panelTopContent>
                    <div :style="{ position: 'sticky', top: '0', zIndex: 1 }">
                        <t-textarea v-model="xhljConferenceInfoSearch" placeholder="请输入关键词搜索" @change="onSearchXhljConferenceInfo" />
                    </div>
                </template>
                <t-option v-for="item in  xhljConferenceInfoOptions" :key="item.value" :value="item.value" :label="item.label"></t-option>
            </t-select>
        </t-form-item>
        <t-form-item label-width="0px">
            <t-space align="end" style="height: 64px">
                <t-button theme="primary" @click="handleQuery">
                    <template #icon> <search-icon /></template>
                    搜索
                </t-button>
                <t-button theme="default" @click="resetQuery">
                    <template #icon> <refresh-icon /></template>
                    重置
                </t-button>
            </t-space>
        </t-form-item>
      </t-form>

      <t-table
        v-model:column-controller-visible="columnControllerVisible"
        :loading="loading"
        hover
        row-key="wonderfulImageId"
        :data="wonderfulImageList"
        :columns="columns"
        :selected-row-keys="ids"
        select-on-row-click
        :pagination="pagination"
        :column-controller="{
          hideTriggerButton: true,
        }"
        :sort="sort"
        show-sort-column-bg-color
        @sort-change="handleSortChange"
        @select-change="handleSelectionChange"
      >
        <template #topContent>
          <t-row>
            <t-col flex="auto">
              <t-button v-hasPermi="['xhlj:wonderfulImage:add']" theme="primary" @click="handleAdd">
                <template #icon> <add-icon /></template>
                新增
              </t-button>
              <t-button
                v-hasPermi="['xhlj:wonderfulImage:edit']"
                theme="default"
                variant="outline"
                :disabled="single"
                @click="handleUpdate()"
              >
                <template #icon> <edit-icon /> </template>
                修改
              </t-button>
              <t-button
                v-hasPermi="['xhlj:wonderfulImage:remove']"
                theme="danger"
                variant="outline"
                :disabled="multiple"
                @click="handleDelete()"
              >
                <template #icon> <delete-icon /> </template>
                删除
              </t-button>
              <t-button v-hasPermi="['xhlj:wonderfulImage:export']" theme="default" variant="outline" @click="handleExport">
                <template #icon> <download-icon /> </template>
                导出
              </t-button>
              <span class="selected-count">已选 {{ ids.length }} 项</span>
            </t-col>
            <t-col flex="none">
              <t-button theme="default" shape="square" variant="outline" @click="showSearch = !showSearch">
                <template #icon> <search-icon /> </template>
              </t-button>
              <t-button theme="default" variant="outline" @click="columnControllerVisible = true">
                <template #icon> <setting-icon /> </template>
                列配置
              </t-button>
            </t-col>
          </t-row>
        </template>


        <template #conferenceInfo="{ row }">
            <span v-if="row.conferenceInfo && Object.keys(row.conferenceInfo).length > 1">
              {{ row.conferenceInfo[Object.keys(row.conferenceInfo)[1]] }}（编号为{{ row.conferenceInfo[Object.keys(row.conferenceInfo)[0]] }}）
            </span>
        </template>

        <template #sysUser="{ row }">
            <span v-if="row.sysUser && Object.keys(row.sysUser).length > 1">
              {{ row.sysUser[Object.keys(row.sysUser)[1]] }}（编号为{{ row.sysUser[Object.keys(row.sysUser)[0]] }}）
            </span>
        </template>

        <template #wonderfulImage="{ row }">
            <image-preview :src="row.wonderfulImage" :width="60" :height="60" />
        </template>



        <template #operation="{ row }">
          <t-space :size="8" break-line>
            <t-link v-hasPermi="['xhlj:wonderfulImage:query']" theme="primary" hover="color" @click.stop="handleDetail(row)">
              <browse-icon />详情
            </t-link>
            <t-link v-hasPermi="['xhlj:wonderfulImage:edit']" theme="primary" hover="color" @click.stop="handleUpdate(row)">
              <edit-icon />修改
            </t-link>
            <t-link v-hasPermi="['xhlj:wonderfulImage:remove']" theme="danger" hover="color" @click.stop="handleDelete(row)">
              <delete-icon />删除
            </t-link>
          </t-space>
        </template>
      </t-table>
    </t-space>
    <!-- 添加或修改精彩图片对话框 -->
    <t-dialog
      v-model:visible="open"
      :header="title"
      destroy-on-close
      :close-on-overlay-click="false"
      width="1100px"
      attach="body"
      :confirm-btn="{
        loading: buttonLoading,
      }"
      @confirm="onConfirm"
    >
      <t-loading :loading="buttonLoading">
        <t-form
          ref="wonderfulImageRef"
          label-align="top"
          :data="form"
          :rules="rules"
          label-width="calc(5em + 41px)"
          scroll-to-first-error="smooth"
          @submit="submitForm"
          layout="inline"
        >

    <t-form-item label="环保新闻" name="conferenceInfo" style="width: 100%">
        <t-select v-model="form.conferenceInfoId"
                  clearable placeholder="请选择环保新闻"
                  :scroll="{ type: 'virtual' }"
                  :popup-props="{ overlayInnerStyle: { height: '150px',width:'500px' } }"
                  auto-width
             >
            <template #prefixIcon>
                <browse-icon style="margin-right: 8px" />
            </template>
            <template #panelTopContent>
                <div :style="{ position: 'sticky', top: '0', zIndex: 1 }">
                    <t-textarea v-model="xhljConferenceInfoSearch" placeholder="请输入关键词搜索" @change="onSearchXhljConferenceInfo" />
                </div>
            </template>
            <t-option v-for="item in xhljConferenceInfoOptions" :key="item.value" :value="item.value" :label="item.label"></t-option>
        </t-select>
    </t-form-item>

          <t-form-item label="精彩图片" name="wonderfulImage" style="width: 100%">
            <image-upload v-model="form.wonderfulImage" :limit="0" />
          </t-form-item>

          <t-form-item label="精彩图片描述" name="wonderfulImageDescription" style="width: 90%">
            <t-textarea v-model="form.wonderfulImageDescription"
                        placeholder="请输入精彩图片描述"
                        name="description"
                        :autosize="{ minRows: 3, maxRows: 6 }"
            />
          </t-form-item>
        </t-form>
      </t-loading>
    </t-dialog>

    <!-- 精彩图片详情 -->
    <t-dialog
      v-model:visible="openView"
      header="精彩图片详情"
      placement="center"
      width="800px"
      attach="body"
      :footer="false"
    >
      <my-descriptions :loading="openViewLoading">

        <t-descriptions-item label="编号">{{ form.wonderfulImageId }}</t-descriptions-item>

        <span v-if="form.conferenceInfo && Object.keys(form.conferenceInfo).length > 1">
              {{ form.conferenceInfo[Object.keys(form.conferenceInfo)[1]] }}（编号为{{ form.conferenceInfo[Object.keys(form.conferenceInfo)[0]] }}）
        </span>

        <span v-if="form.sysUser && Object.keys(form.sysUser).length > 1">
              {{ form.sysUser[Object.keys(form.sysUser)[1]] }}（编号为{{ form.sysUser[Object.keys(form.sysUser)[0]] }}）
        </span>

        <t-descriptions-item label="精彩图片">
          <image-preview :src="form.wonderfulImage" :width="60" :height="60" />
        </t-descriptions-item>

        <t-descriptions-item label="精彩图片描述" :span="2">{{ form.wonderfulImageDescription }}</t-descriptions-item>

        <t-descriptions-item label="创建时间">{{ parseTime(form.createTime) }}</t-descriptions-item>

      </my-descriptions>
    </t-dialog>
  </t-card>
</template>

<script lang="tsx" setup>
defineOptions({
  name: 'WonderfulImage',
});
import {
  AddIcon,
  DeleteIcon,
  DownloadIcon,
  EditIcon,
  RefreshIcon,
  SearchIcon,
  SettingIcon,
  BrowseIcon,
  BookIcon
} from 'tdesign-icons-vue-next';
import type { SelectProps, TextareaProps, FormInstanceFunctions, FormRule, PageInfo, PrimaryTableCol, SubmitContext, TableSort } from 'tdesign-vue-next';
import { computed, getCurrentInstance, ref } from 'vue';
import { ArrayOps } from '@/utils/array';

import type { XhljWonderfulImageForm, XhljWonderfulImageQuery, XhljWonderfulImageVo } from '@/api/xhlj/model/wonderfulImageModel';
import { listWonderfulImage, getWonderfulImage, delWonderfulImage, addWonderfulImage, updateWonderfulImage } from '@/api/xhlj/wonderfulImage';
import type { XhljConferenceInfoQuery } from '@/api/xhlj/model/conferenceInfo';
import { listConferenceInfo } from '@/api/xhlj/conferenceInfo';


const { proxy } = getCurrentInstance();

const openView = ref(false);
const openViewLoading = ref(false);
const wonderfulImageRef = ref<FormInstanceFunctions>();
const open = ref(false);
const buttonLoading = ref(false);
const title = ref('');
const wonderfulImageList = ref<XhljWonderfulImageVo[]>([]);
const loading = ref(false);
const columnControllerVisible = ref(false);
const showSearch = ref(true);
const total = ref(0);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const sort = ref<TableSort>();
const xhljConferenceInfoQueryParams = ref<XhljConferenceInfoQuery>({
    pageNum: 1,
    pageSize: 10000,
});
const xhljConferenceInfoList = ref<SelectProps['options']>([]);
const xhljConferenceInfoOptions = ref<SelectProps['options']>([]);
const xhljConferenceInfoSearch = ref('');
const onSearchXhljConferenceInfo = () => {
        xhljConferenceInfoOptions.value = xhljConferenceInfoList.value
            .map((item) => ({
                label: item[Object.keys(item)[1]],
                value: item[Object.keys(item)[0]],
            }))
            .filter(option => option.label.includes(xhljConferenceInfoSearch.value));
};
/** 查询环保新闻列表 */
async function getXhljConferenceInfoList() {
    listConferenceInfo(xhljConferenceInfoQueryParams.value)
        .then((response) => {
            xhljConferenceInfoList.value = response.rows;
            const labelValue = response.rows.map((item) => ({
                label: item[Object.keys(item)[1]],
                value: item[Object.keys(item)[0]],
            }));
            xhljConferenceInfoOptions.value = labelValue;
            console.log("xhljConferenceInfoList", xhljConferenceInfoList.value)
            console.log("xhljConferenceInfoOptions", xhljConferenceInfoOptions)
        })
}

// 校验规则
const rules = ref<Record<string, Array<FormRule>>>({
});
// 列显隐信息
const columns = ref<Array<PrimaryTableCol>>([
  { title: `选择列`, colKey: 'row-select', type: 'multiple', width: 50, align: 'center',fixed: 'left' },
  { title: `编号`, colKey: 'wonderfulImageId', align: 'center', ellipsis: {theme: 'light'} ,fixed: 'left'},
  { title: `环保新闻`, colKey: 'conferenceInfo', align: 'center', minWidth: 155, ellipsis: {theme: 'light'},
        className: ({ row }) => {
            return 'custom-cell-class-name';
        },
        attrs: ({ row }) => {
            return {
                style: {
                    color: '#fff', // 白色文字
                    fontWeight: 'bold', // 字体加粗
                    background: 'linear-gradient(to right, #4facfe 0%, #00f2fe 100%)', // 渐变背景
                    transition: 'all 0.3s ease', // 添加过渡效果
                    borderRadius: '4px', // 圆角
                }
            };
        }
,
  },
  { title: `系统用户`, colKey: 'sysUser', align: 'center', minWidth: 155, ellipsis: {theme: 'light'},
  },
  { title: `精彩图片`, colKey: 'wonderfulImage', align: 'center', minWidth: 160 },
  { title: `精彩图片描述`, colKey: 'wonderfulImageDescription', align: 'center', minWidth: 140,  ellipsis: {theme: 'light'} },
  { title: `创建时间`, colKey: 'createTime', align: 'center', minWidth: 112, width: 120, sorter: true },
  { title: `操作`, colKey: 'operation', align: 'center', width: 120 , fixed: 'right'},
]);
// 提交表单对象
const form = ref<XhljWonderfulImageVo & XhljWonderfulImageForm>({});
// 查询对象
const queryParams = ref<XhljWonderfulImageQuery>({
  pageNum: 1,
  pageSize: 10,
  wonderfulImageId: undefined,
  conferenceInfo: undefined,
  sysUser: undefined,
});
// 分页
const pagination = computed(() => {
  return {
    current: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    total: total.value,
    showJumper: true,
    onChange: (pageInfo: PageInfo) => {
      queryParams.value.pageNum = pageInfo.current;
      queryParams.value.pageSize = pageInfo.pageSize;
      getList();
    },
  };
});

/** 查询精彩图片列表 */
function getList() {
  loading.value = true;
  listWonderfulImage(queryParams.value)
    .then((response) => {
      wonderfulImageList.value = response.rows;
      total.value = response.total;
      console.log("WonderfulImage", response.rows)
    })
    .finally(() => (loading.value = false));
}

// 表单重置
function reset() {
  form.value = {};
  proxy.resetForm('wonderfulImageRef');
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef');
  queryParams.value.pageNum = 1;
  handleSortChange(null);
}

/** 排序触发事件 */
function handleSortChange(value?: TableSort) {
  sort.value = value;
  if (Array.isArray(value)) {
    queryParams.value.orderByColumn = value.map((item) => item.sortBy).join(',');
    queryParams.value.isAsc = value.map((item) => (item.descending ? 'descending' : 'ascending')).join(',');
  } else {
    queryParams.value.orderByColumn = value?.sortBy;
    queryParams.value.isAsc = value?.descending ? 'descending' : 'ascending';
  }
  getList();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: Array<string | number>) {
  ids.value = selection;
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = '添加精彩图片';
}

/** 详情按钮操作 */
function handleDetail(row: XhljWonderfulImageVo) {
  reset();
  openView.value = true;
  openViewLoading.value = true;
  const wonderfulImageId = row.wonderfulImageId;
  getWonderfulImage(wonderfulImageId).then((response) => {
    form.value = response.data;
    openViewLoading.value = false;
  });
}

/** 修改按钮操作 */
function handleUpdate(row?: XhljWonderfulImageVo) {
  buttonLoading.value = true;
  reset();
  open.value = true;
  title.value = '修改精彩图片';
  const wonderfulImageId = row?.wonderfulImageId || ids.value.at(0);
  getWonderfulImage(wonderfulImageId).then((response) => {
    buttonLoading.value = false;
    form.value = response.data;
  });
}

/** 提交按钮 */
function onConfirm() {
  wonderfulImageRef.value.submit();
}

/** 提交表单 */
function submitForm({ validateResult, firstError }: SubmitContext) {
  if (validateResult === true) {
    buttonLoading.value = true;
    const msgLoading = proxy.$modal.msgLoading('提交中...');
    if (form.value.wonderfulImageId) {
      updateWonderfulImage(form.value)
        .then(() => {
          proxy.$modal.msgSuccess('修改成功');
          open.value = false;
          getList();
        })
        .finally(() => {
          buttonLoading.value = false;
          proxy.$modal.msgClose(msgLoading);
        });
    } else {
      addWonderfulImage(form.value)
        .then(() => {
          proxy.$modal.msgSuccess('新增成功');
          open.value = false;
          getList();
        })
        .finally(() => {
          buttonLoading.value = false;
          proxy.$modal.msgClose(msgLoading);
        });
    }
  } else {
    proxy.$modal.msgError(firstError);
  }
}

/** 删除按钮操作 */
function handleDelete(row?: XhljWonderfulImageVo) {
  const wonderfulImageIds = row?.wonderfulImageId || ids.value;
  proxy.$modal.confirm(`是否确认删除精彩图片编号为${wonderfulImageIds}的数据项？`, () => {
    const msgLoading = proxy.$modal.msgLoading('正在删除中...');
    return delWonderfulImage(wonderfulImageIds)
      .then(() => {
        ids.value = ArrayOps.fastDeleteElement(ids.value, wonderfulImageIds);
        getList();
        proxy.$modal.msgSuccess('删除成功');
      })
      .finally(() => {
        proxy.$modal.msgClose(msgLoading);
      });
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'xhlj/wonderfulImage/export',
    {
      ...queryParams.value,
    },
    `wonderfulImage_${new Date().getTime()}.xlsx`,
  );
}

onMounted(() => {
    getXhljConferenceInfoList();
    getList();
})


</script>
<style>
    .t-table td.custom-cell-class-name {
        font-size: 16px;
        padding: 10px;
        text-shadow: none;
        transition: transform 0.3s ease, text-shadow 0.3s ease;
    }
    .t-table td.custom-cell-class-name:hover {
        transform: scale(1.05); /* 缩放动画 */
        text-shadow: 0 0 4px rgba(0, 0, 0, 0.5); /* 文字阴影动画 */
        background: linear-gradient(to right, #00f2fe 0%, #4facfe 100%); /* 悬停时背景色渐变方向反转 */
    }
    .custom-link {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        background: linear-gradient(to right, #007bff, #0056b3);
        color: white;
        padding: 8px 16px;
        margin-top: 5px;
        border-radius: 20px;
        text-decoration: none;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        transition: all 0.3s ease-in-out;
    }
    .custom-link:hover {
        background: linear-gradient(to right, #0056b3, #007bff);
        transform: translateY(-2px) scale(1.03);
        box-shadow: 0 6px 8px rgba(0,0,0,0.2);
    }
</style>
